<template>
  <el-container>
      <el-header>注册/登入</el-header>
      <el-main>
        <el-form label-position = "top"
                 ref="accForms"
                 :model="form" :rules="rules"
        >
          <el-form-item label="账号" prop="account" >
            <el-input v-model="form.account" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="密码" prop="password" >
            <el-input
                  v-model="form.password"
                  type="password"
                  placeholder="请输入密码"
                  show-password
              />
          </el-form-item>
          <el-form-item label="邀请码" prop="inviteCode" >
              <el-input
                      v-model="form.inviteCode"
                      placeholder="请输入邀请码"
              />
          </el-form-item>
        </el-form>
        <div>
          <el-button type="primary" @click="commit(1)" :loading = "load">登入</el-button>
          <el-button type="success"  @click="commit(2)" :loading = "load">注册</el-button>
        </div>
      </el-main>
  </el-container>
</template>

<script setup>
import {ref, getCurrentInstance, reactive,unref,onMounted} from "vue";
import {login, register,get_user} from "@/axios/login";
import store from "@/store";
import {useRouter,useRoute} from 'vue-router'


const router = useRouter();
const route = useRoute();
const urlll = route.query.urlll

onMounted(() => {
  if(!urlll){
    get_user().then(res =>{
      if(res.data.data.username){
        router.push("/")
      }
    }).catch(err=>{

    })
  }
})


let load = false;
const {proxy} =getCurrentInstance();
const accForms = ref(null);
const form = reactive({
  account: '',
  password:'',
  inviteCode:""
})
const rules = {
  account:[{ required: true, message: '账号不能为空', trigger: 'blur'}],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur'}],
}


const commit = (e) => {
  load = true;
  unref(accForms).validate((valid) => {
    if (valid) {
      let parmas = {}
      parmas.username = form.account
      parmas.password = form.password
      parmas.inviteCode = form.inviteCode
      if (1 == e){
        loginCommit(parmas)
      }
      if (2 == e){
        registerCommit(parmas)
      }
    }
  })
}



   const loginCommit = (parmas) =>{
     login(parmas).then(res=>{
       store.commit("setToke",res.data.access_token)
       store.commit("setReToke", res.data.refresh_token)
       if(urlll){
         router.push(urlll)
       }else {
        router.push("/")
       }
     }).then(()=>{
       load = false;
     }).catch(err=>{
       load = false;
     })
   };
   const registerCommit = (parmas) => {
     register(parmas).then(res => {
       if(res.data.code === 0){
        loginCommit(parmas);
       }
       load = false;
     }).catch(err => {
       load = false;
     })
   }



</script>

<style scoped>
  .el-header{
      line-height: 60px;
  }
  .el-container{

      background-color: #FFFFFF;
  }


</style>